import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Error from "../../pages/Error.vue";
import Login from "../../pages/Login.vue";
import { useUserState } from "../../store";
import ACCESS_ENUM from "../../assets/content/ACCESS_ENUM";
import { ElMessage } from "element-plus";
import { routeList } from "./routes";

// 确保 routeList 已经正确导入
if (!routeList) {
  throw new Error("routeList is undefined");
}

const otherRouteList = [
  {
    path: "/error",
    name: "错误页",
    component: Error,
  },
  {
    path: "/login",
    name: "登录",
    component: Login,
  },
];

// 使用扩展运算符确保 routeList 是可迭代的
const routes: Array<RouteRecordRaw> = [...routeList];
const otherRoutes: Array<RouteRecordRaw> = [...otherRouteList];

// 将路由数组添加到总数组
otherRoutes.push(...routes);

// 路由
const router = createRouter({
  // 采用hash模式
  history: createWebHashHistory(),
  routes: otherRoutes,
});

// 全局动态路由
// 路由跳转之前执行
router.beforeEach(async (to, from, next) => {
  // 必须在这里进行导入
  const { checkUserAccess, getLoginUserState } = useUserState();

  // 获取用户加载状态
  await getLoginUserState();

  // 判断是否存在该路由
  if (to.matched.length === 0) {
    next("/error");
    ElMessage.error("页面不存在");
  }

  if (
    // 路由守卫 判断是否为管理员 不为管理员直接跳转到主页
    to.meta.access === ACCESS_ENUM.ADMIN &&
    !checkUserAccess(ACCESS_ENUM.ADMIN)
  ) {
    next("/");
    ElMessage.error("权限错误，不为管理员");
  } else {
    next();
  }
});

export default router;
